const io = require('socket.io')(8900, {
      cors: {
            origin: "http://127.0.0.1:5173"
      }
})

let users = []

const addUser = (userId, socketId) => {
      !users.some((user) => user.userId === userId) && users.push({ userId, socketId });
}

io.on('connection', (socket) => {
      console.log('a user connected');
      // take user name and push it to array
      socket.on('addUser', (userId) => {
            addUser(userId, socket.id);
            io.emit('getUsers', users);
      })

      socket.on('sendMessage', ({ senderId, receiverId, text }) => {
            const user = users.find((user) => user.userId === receiverId);
            io.to(user.socketId).emit('getMessage', { senderId, text });
      })

      socket.on('disconnect', () => {
            console.log('a user disconnected')
            console.log(socket.id, users)
            users = users.filter((user) => user.socketId !== socket.id)
            io.emit('getUsers', users)
      })
});
